package com.hanmiao.proxy;  
  
import java.lang.reflect.Method;  
  
import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;  
  
import net.sf.cglib.proxy.Enhancer;  
import net.sf.cglib.proxy.MethodInterceptor;  
import net.sf.cglib.proxy.MethodProxy;  
//动态代理功能演示
//需引入 cglib-2.1.3.jar 和 asm.jar 以完成编译运行  
public class CGLibProxy implements MethodInterceptor {  
  
    public static CGLibProxy getInstance(){  
        return Holder.instance;  
    }  
  
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {  
        before(obj, method, args);  
        Object result = proxy.invokeSuper(obj, args);  
        after(obj, method, args);  
        return result;  
    }  
  
    private void before(Object obj, Method method, Object[] args){  
        logger.info("Before method {} invoking...", method.getName());  
    }  
  
    private void after(Object obj, Method method, Object[] args){  
        logger.info("After method {} invoking...", method.getName());  
    }  
  
    //生成不带参数的代理类  
    @SuppressWarnings("unchecked")  
    public <T> T getProxy(Class<T> clazz) {  
        return (T) Enhancer.create(clazz, this);  
    }  
  
    //生成有参数的代理类，target是代理目标，argsType 是各个参数的类型，argsValue 是各个参数的值  
    @SuppressWarnings("unchecked")  
    public <T>T createProxy(T target, Class<T>[] argsType, Object[] argsValue){  
        Enhancer enhancer = new Enhancer();  
        enhancer.setSuperclass(target.getClass());  
        enhancer.setCallback(this);  
        return (T)enhancer.create(argsType, argsValue);  
    }  
  
    private static class Holder{  
        private static final CGLibProxy instance = new CGLibProxy();  
    }  
  
    private Logger logger = LoggerFactory.getLogger(this.getClass());  
}